package com.lmx.repoDomain.repository;

import io.katharsis.repository.annotations.JsonApiResourceRepository;
import io.katharsis.repository.annotations.JsonApiSave;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.lmx.common.constants.CommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.SMSUtil;
import com.lmx.persistence.service.UserService;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.business.User;
import com.lmx.repoDomain.tmodel.unpersis.ResetPassword;
import com.lmx.repoDomain.tmodel.unpersis.TempVerificationCode;

/**
 * 重置密码
 *
 * @author ytche
 * @date 2017年9月8日
 *
 */
@JsonApiResourceRepository(value = ResetPassword.class)
@Component
public class ResetPasswordRepository extends BaseRepository<ResetPassword> {
	@Autowired
	private UserService<User> userService;

	@SuppressWarnings("unchecked")
	@Override
	@JsonApiSave
	public ResetPassword save(final ResetPassword entity) {
		String type = entity.getType();
		String mobile = entity.getMobile();

		List<User> users = Lists.newArrayList();
		switch (type) {
		case CommonConstants.SEND_RESET_CODE:
			users = this.userService.findUsersByLoginName(mobile);
			if (users == null || users.size() < 1) {
				throw new BusinessException("",
						CommonConstants.RESET_PASSWORD_ERROR.NO_USER.lable(), "不存在该手机号绑定的用户");
			}
			Integer code = SMSUtil.getInstance().sendResetCode(mobile);
			TempVerificationCode tempCodeEntity = new TempVerificationCode(mobile, code);
			ActionContextHolder.putTempCode(mobile, tempCodeEntity);
			break;
		case CommonConstants.CHECK_CODE:
			if (StringUtils.isBlank(mobile) || entity.getCode() == null) {
				throw new BusinessException("",
						CommonConstants.RESET_PASSWORD_ERROR.INFO_NULL.lable(), "手机号或者验证码不能为空");
			}
			if (!ActionContextHolder.getTempCode().containsKey(mobile)
					|| !(entity.getCode().equals(ActionContextHolder.getTempCode().get(mobile)
							.getCode()))) {
				throw new BusinessException("",
						CommonConstants.RESET_PASSWORD_ERROR.CHECK_FAIL.lable(), "手机号与验证码不匹配");
			}
			break;
		case CommonConstants.RESET_PASSWORD:
			if (StringUtils.isBlank(mobile) || StringUtils.isBlank(entity.getPassword())) {
				throw new BusinessException("",
						CommonConstants.RESET_PASSWORD_ERROR.INFO_NULL.lable(), "手机号或者密码不能为空");
			}
			this.userService.resetPassword(mobile, entity.getPassword());
			break;
		default:
			break;
		}
		return entity;
	}
}
